package main

import (
	"flag"
	"fmt"
	"image"
	"os"

	"github.com/disintegration/imaging"
)

func fileExists(file string) bool {
	if _, err := os.Stat(file); os.IsNotExist(err) {
		return false
	}

	return true
}

func main() {
	var width, height, count int
	var filename string
	flag.IntVar(&width, "width", 0, "spritesheet cell width")
	flag.IntVar(&height, "height", 0, "spritesheet cell height")
	flag.IntVar(&count, "count", 0, "spritesheet cell count")
	flag.StringVar(&filename, "filename", "", "spritesheet image file")
	flag.Parse()

	if width <= 0 || height <= 0 || count <= 0 {
		fmt.Println("extract-sp.exe -filename=example.png -width=81 -height=117 -count=54")
		return
	}

	img, err := imaging.Open(filename)
	if err != nil {
		fmt.Println("打开文件失败：", err)
		return
	}

	if !fileExists("output") {
		err = os.Mkdir("output", 0600)
		if err != nil {
			fmt.Println("创建输出目录失败：", err)
			return
		}
	}

	col := img.Bounds().Size().X / width
	row := img.Bounds().Size().Y / height

	cnt := 0
	for r := 0; r < row; r++ {
		for c := 0; c < col; c++ {
			cnt++
			part := imaging.Crop(img, image.Rect(c*width, r*height, (c+1)*width, (r+1)*height))

			imaging.Save(part, fmt.Sprintf("output/%d.png", cnt))
			if cnt >= count {
				break
			}
		}
	}

	// imaging.Crop
}
